package com.taikang.hmp.hservice.doctor.pm25.service;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisClient {
    private JedisPool jedisPool = null;
    
    private String address = "";
    private int port = 0;
    
    public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
	private JedisPool getJedisPool() {
		if (this.jedisPool == null) {
			JedisPoolConfig config = new JedisPoolConfig();
	        config.setMaxActive(-1);
	        config.setMaxIdle(5);
	        config.setMaxWait(1000l);
	        config.setTestOnBorrow(false); 
	        this.jedisPool = new JedisPool(config, this.getAddress(), this.getPort());
		}
		
		return this.jedisPool;
	}
	
	private Jedis getJedis() {
		return this.getJedisPool().getResource();
	}
	
    private void returnResource(Jedis jedis) {
        if (jedis != null) {
        	this.getJedisPool().returnResource(jedis);
        }
    }
    
    public String get(String key) {
        String value = null;

        Jedis jedis = null;
        try {
        	jedis = this.getJedis();
        	value = jedis.get(key);
        } catch (Exception e) {
        	this.getJedisPool().returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            this.returnResource(jedis);
        }

        return value;
    }
    
    public void set(String key, String value, int expire) {
        Jedis jedis = null;
        try {
        	jedis = this.getJedis();
        	jedis.set(key, value);
        	jedis.expire(key, expire);
        } catch (Exception e) {
        	this.getJedisPool().returnBrokenResource(jedis);
            e.printStackTrace();
        } finally {
            this.returnResource(jedis);
        }
    }
}
